//后台工厂图片业务代码
const factoryPicModel = require("../models/factoryPic.js");
const path = require("path")
const moment = require("moment");
const fs = require('fs').promises;
class factoryPicController {
    //添加表单
    static showAddPicForm(req, res) {
        res.render("factoryPic-add", { title: '工厂图片添加' })
    }
    //工厂照片列表显示
    static async getPicList(req, res) {
        //console.log(path.join(__dirname, "../public/uploads"))
        let { page = 1, size = 4 } = req.query;
        page = parseInt(page);
        size = parseInt(size);
        // let count = await factoryPicModel.count();
        let count = await factoryPicModel.countDocuments();
        let offset = (page - 1) * size;
        let totalPage = Math.ceil(count / size);
        let infos = await factoryPicModel.find().limit(size).skip(offset);
        res.render("factoryPic-list", { title: "工厂图片展示", page, size, totalPage, infos, moment })

    }
    //添加操作
    static async addPic(req, res) {
        let src = "";
        if (req.file) {
            src = req.file.filename;
        }
        let { title, isLock, hot } = req.body;
        let factoryPicObj = new factoryPicModel({ title, src, isLock, hot });
        let error = factoryPicObj.validateSync();
        if (error) {
            const errorRs = [];
            for (let attr in error.errors) {
                errorRs.push(`${factoryPicModel.fields[attr]}:${error.errors[attr]}`)
            }
            let time = 5;
            let url = "/admin/factoryPic/add"
            res.render("error", { errorRs, time, url });
            return;
        } else {
            try {
                await factoryPicObj.save();//保存记录
                res.redirect("/admin/factoryPic/list");
            } catch (e) {
                res.redirect("/admin//factoryPic/add");
            }
        }

    }
    //工厂照片删除操作
    static async delPic(req, res) {
        //
        let picId = req.params.id;
        try {
            let info = await factoryPicModel.findOneAndDelete({ _id: picId });
            //同时删除图片
            await fs.unlink(path.join(__dirname, `../public/uploads/${info.src}`))
        } catch (e) {
            console.log(e);
        } finally {
            res.redirect("back")
        }
    }
    //工厂照片编辑表单显示
    static async showPicEditForm(req, res) {
        let info = await factoryPicModel.findById(req.params.id);
        res.render("factoryPic-edit", { title: '工厂图片编辑', info })
    }
    //编辑操作
    static async editPic(req, res) {
        //res.json(req.body)
        let src = "";
        if (req.file) {
            src = req.file.filename;
        }
        let { _id, title, isLock, hot } = req.body;
        factoryPicModel.findOne({ _id }, async (error, data) => {
            if (error) {
                res.redirect("back")
            } else {
                data.title = title;
                data.isLock = isLock;
                if (src) {//有文件上传才修改
                    data.src = src;
                }
                data.hot = hot;
                await data.save();
                res.redirect("/admin/factoryPic/list")
            }
        })
    }
}

module.exports = factoryPicController